//
//  StatusDAL.swift
//  Weibo
//
//  Created by 孙明海 on 16/2/27.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import Foundation
/// 最大缓存时间
private let maxCacheDataTime: NSTimeInterval = 7 * 60 * 60

/// 数据访问层  - 目标: 专门负责处理本地 SQLite 和 网络数据
class StatusDAL {
    
    /// 清除过期的缓存数据
    class func clearCacheData() {
        let date = NSDate(timeIntervalSinceNow: -maxCacheDataTime)
        // 2016-02-27 22:14:58
        let dfmt = NSDateFormatter()
        dfmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateStr = dfmt.stringFromDate(date)
        
        let sql = "DELETE FROM T_Status WHERE createTime < ?;"
        
        SQLiteManager.sharedManager.queue.inDatabase { (db) -> Void in
            if db.executeUpdate(sql, dateStr) {
                print("删除了 \(db.changes()) 数据")
            }
        }
        
    }
    
    /// 从网络加载数据
    class func loadStatus(since_id: Int, max_id: Int, callBack: (array:  [[String: AnyObject]]?) -> () ) {
        
        let array = checkCacheData(since_id, max_id: max_id)
        if array?.count > 0 {
            print("查询到缓存数据 \(array?.count)")
            callBack(array: array)
            return
        }
        
        
        NetworkTools.sharedNetworkTools.loadStatus(since_id: since_id, max_id: max_id) { (result, error) -> (Void) in
            if error != nil {
                print("数据加载出错")
                callBack(array: nil)
                return
            }
            
            guard let array = result?["statuses"] as? [[String: AnyObject]] else {
                print("数据格式出错")
                callBack(array: nil)
                return
            }
            
            StatusDAL.saveCacheData(array)
            callBack(array: array)
        }
    }
    
    private class func checkCacheData(since_id: Int, max_id: Int) -> [[String: AnyObject]]? {
        
        guard let userId = UserAccountViewModel.sharedUserAccount.account?.uid else {
            print("用户没有登录")
            return nil
        }
        
        var sql = "SELECT statusId, status, userId FROM T_Status \n"
        sql += "WHERE userId = \(userId)"
        if since_id > 0 { //下拉刷新
            sql += "    AND statusId > \(since_id)"
        } else if max_id > 0 { // 上拉刷新
            sql += "    AND statusId < \(max_id)"
        }
        
        sql += "    ORDER BY statusId DESC LIMIT 20;"
        print(sql)
        
        let array = SQLiteManager.sharedManager.execRecordSet(sql)
        var arrayM = [[String: AnyObject]]()
        for dict in array {
            let jsonData = try! NSJSONSerialization.JSONObjectWithData(dict["status"] as! NSData, options: []) as! [String: AnyObject]
            arrayM.append(jsonData)
        }
        
        return arrayM
    }
    
    /// 保存数据
    ///
    /// - parameter array: 从网络加载的数据
    class func saveCacheData(array: [[String: AnyObject]]) {
        guard let userId = UserAccountViewModel.sharedUserAccount.account?.uid else {
            print("用户没有登录")
            return
        }
        
        let sql = "INSERT OR REPLACE INTO T_Status (statusId,status,userId) VALUES (?,?,?);"
        
        SQLiteManager.sharedManager.queue.inTransaction { (db, rollback) -> Void in
            
            for dict in array {
                let statusId = dict["id"] as! Int
                let status = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])

                if !db.executeUpdate(sql, statusId, status, userId) {
                    rollback.memory = true
                    return
                }
            }
        }
        print("插入数据完成")
    }
}